<?php

/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2023-05-07 09:37:06
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2023-07-28 14:28:21
 */

namespace Common\Services\Sys;

use Common\BaseService;
use Common\Component\Singleton;
use Common\Helpers\DebugHelper;
use Common\Models\sys\SysDeviceCallback;
use Common\Models\sys\SysDeviceCate;
use Common\Models\sys\SysProject;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Collection;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Stringable\Str;
use Psr\EventDispatcher\EventDispatcherInterface;

class ProjectService extends BaseService
{
    use Singleton;

    /**
     * @var EventDispatcherInterface
     */
    #[Inject]
    private EventDispatcherInterface $eventDispatcher;

    public function __construct(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    public static function addProject(string $title, string $desc, int $member_id): Collection|array
    {
        $SysProject = new SysProject();
        $Res = $SysProject->addInfo([
            'title' => $title,
            'desc' => $desc,
            'member_id' => $member_id,
            'AppKey' => self::createAppKey(),
            'AppSecret' => self::createAppSecret(),
            'project_sn' => Str::random(30),
        ]);

        return $SysProject->query()->where(['id' => $Res])->get();
    }

    public static function createAppKey(): string
    {
        $AppKey = Str::random(32);
        return strtoupper($AppKey);
    }


    public static function createAppSecret(): string
    {
        $AppSecret = Str::random(32);
        return strtoupper($AppSecret);
    }

    public static function getProjectByMid($member_id)
    {
        $SysProject = new SysProject();
        $where = [];
        $where['member_id'] = $member_id;

        return $SysProject->query()->where($where)->value('id');
    }

    /**
     * 根据域名获取项目信息
     * @param $project_sn
     * @param $domain
     * @return Collection|array
     */
    public static function getProjectByDomain($project_sn,$domain): Collection|array
    {
        $SysProject = new SysProject();
        $where = [];
        /**
         * 放行小程序
         */
        if ($domain != 'servicewechat.com'){
            $where['domain'] = $domain;
        }
        $where['project_sn'] = $project_sn;
        $project = $SysProject->query()->where($where)->first();

        return $project?$project->toArray():[];
    }

    public static function getProjectByAppId($project_sn,$appId): array
    {
        $SysProject = new SysProject();
        $where = [];
        $where['project_sn'] = $project_sn;
        $where['app_id'] = $appId;

        $project = $SysProject->query()->where($where)->first();

        return $project?$project->toArray():[];
    }

    public static function getProjectByAppKey($appKey)
    {
        $SysProject = new SysProject();
        $where = [];
        $where['appKey'] = $appKey;

        return $SysProject->query()->where($where)->value('id');
    }

    public static function listProject($page, $pageSize, string $keyWords = ''): array
    {
        $SysProject = new SysProject();
        $where = [];
        if ($keyWords) {
            $where['title'] = ['%' . $keyWords . '%', 'like'];
        }
        return $SysProject->getAll($page, $pageSize, $where);
    }

    public static function listProjectAll($columns = ['*']): array
    {
        $SysProject = new SysProject();
        $list = $SysProject::query()->first($columns)->all();
        return $list?$list->toArray():[];
    }

    public static function detailProject($id): array
    {
        $SysProject = new SysProject();
        $where['id'] = $id;
        $project = $SysProject->query()->where($where)->first();
        $device = $project->toArray();
        $cates = [];
        if ($device) {
            $cate_id = array_unique(array_column($device, 'cate_pid'));
            // 获取所有的分类
            $cates = SysDeviceCate::query()->where('id', $cate_id, 'in')->all();
        }
        return [
            'project' => $project,
            'device' => $device,
            'cates' => $cates,
        ];
    }

    public static function editProject(int $id, string $title, string $desc): bool
    {
        $SysProject = new SysProject();
        return $SysProject->updateInfo([
            'title' => $title,
            'desc' => $desc,
        ], [
            'id' => $id,
        ]);
    }

    public static function deleteProject(int $id)
    {
        $SysProject = new SysProject();
        $Res = $SysProject->delInfo(['id' => $id]);
        if (!$Res) {
            return self::responseData(400, [], '删除失败');
        }

        return $Res;
    }

    public static function setBackUrl(int $member_id, int $project_id, string $url): bool|array|null
    {
        $SysDeviceCallback = new SysDeviceCallback();
        $isHave = $SysDeviceCallback->query()->where([
            'member_id' => $member_id,
            'project_id' => $project_id
        ])->get();
        if (!$isHave) {
            $Res = $SysDeviceCallback->addInfo([
                'member_id' => $member_id,
                'project_id' => $project_id,
                'url' => $url,
            ]);
        } else {
            $Res = $SysDeviceCallback->updateInfo([
                'url' => $url
            ], [
                'member_id' => $member_id,
                'project_id' => $project_id,
            ]);
        }

        if (!$Res) {
            return self::responseData(400, [], '设置失败');
        }

        return true;
    }

}
